package com.oocl.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.oocl.pojo.OrderInfo;
import com.oocl.pojo.Orders;
import com.oocl.pojo.User;
import com.oocl.service.OrderManager;
import com.oocl.service.impl.OrderManagerImpl;
import com.oocl.util.InstanceFactory;

/**
 * Servlet implementation class CartServlet
 */
public class BuyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Logger logger = Logger.getLogger(BuyServlet.class);
	private OrderManager manager;
 
    public BuyServlet() {
        super();
        manager = InstanceFactory.newInstance(OrderManagerImpl.class);
    }

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		Map<String, OrderInfo> carts = (Map<String, OrderInfo>) request.getSession().getAttribute("cart");
		if(null==carts){
			request.setAttribute("result", "你未选择任何商品!");
			request.getRequestDispatcher("store").forward(request, response);
			return;
		}
		List<Orders> orders = new ArrayList<>();
		for(String s:carts.keySet()){
			orders.add(toOrder(carts.get(s)));
		}
		int m = manager.addOrders(orders);
		if(m>0){
			logger.info(((User)request.getSession().getAttribute("user")).getUsername()+" buy books success");
			request.getSession().removeAttribute("cart");
			System.out.println("购买成功");
		}else {
			System.out.println("购买失败");
		}
		request.getRequestDispatcher("../WEB-INF/cart.jsp").forward(request, response);
	}

	private Orders toOrder(OrderInfo orderInfo) {
		Orders o = new Orders();
		o.setBookId(orderInfo.getBookId());
		o.setCount(orderInfo.getCount());
		o.setUserId(orderInfo.getUserId());
		return o;
	}


}
